from flask import Flask, request, jsonify
from flask_cors import CORS
import os

from ocr_Service import OCRService
from ai_chat import AIChat
# 初始化核心组件
app = Flask(__name__)
CORS(app)  # 启用跨域

# 初始化服务模块
deepseek_chat = AIChat()

ocr_service = OCRService()

@app.route('/chat', methods=['POST'])
def chat_endpoint():
    """处理对话请求"""
    return deepseek_chat.chat()

@app.route('/save', methods=['POST'])
def save_dialog():
    """保存对话状态"""
    return deepseek_chat.save()

@app.route('/load', methods=['POST'])
def load_dialog():
    """加载对话历史"""
    return deepseek_chat.load()

@app.route('/ocr', methods=['POST'])
def ocr_processing():
    """处理图片OCR识别（内存模式）"""
    try:
        if 'file' not in request.files:
            return jsonify({"error": "未上传图片文件"}), 400
            
        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "空文件名"}), 400

        # 验证文件类型
        ext = os.path.splitext(file.filename)[1].lower()
        if ext not in ['.png', '.jpg', '.jpeg']:
            return jsonify({"error": "仅支持PNG/JPG格式"}), 400

        # 直接读取文件内容到内存
        image_data = file.read()
        result = ocr_service.process_image(image_data)

        return jsonify({
            "result": result
        }), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/check')
def health_check():
    """服务健康检查"""
    return jsonify({
        "status": "running",
        "services": ["chat", "ocr"]
    }), 200

if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=5000,
        threaded=True,
        debug=os.getenv('FLASK_DEBUG', 'false').lower() == 'true'
    )